package com.xaicode.auth.utils;

import org.redisson.api.RBucket;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedissonUtil {

    private final RedissonClient redisson;

    public RedissonUtil(RedissonClient redisson) {
        this.redisson = redisson;
    }


    public RedissonClient getRedisson() {
        return redisson;
    }

    /**
     * 存入REDIS, String类型
     *
     * @param key   key值
     * @param value value值
     */
    public void setBucket(String key, String value) {
        RBucket<String> rBucket = redisson.getBucket(key);
        rBucket.set(value);
    }

    /**
     * 存入REDIS, String类型，有过期时间
     *
     * @param key      key值
     * @param value    value值
     * @param times    过期时间
     * @param timeUnit 过期时间单位
     */
    public void setBucket(String key, String value, long times, TimeUnit timeUnit) {
        RBucket<String> rBucket = redisson.getBucket(key);
        rBucket.set(value, times, timeUnit);
    }

    /**
     * 获取桶对象
     *
     * @param key key值
     * @return .
     */
    public String getBucket(String key) {
        RBucket<String> rBucket = redisson.getBucket(key);
        return rBucket.get();
    }

    /**
     * 获取桶
     *
     * @param key key值
     */
    public boolean removeBucket(String key) {
        RBucket<String> rBucket = redisson.getBucket(key);
        return rBucket.delete();
    }

    /**
     * 获取锁
     *
     * @param lockName 锁名
     * @return .
     */
    public RLock getLock(String lockName) {
        return redisson.getLock(lockName);
    }

}
